// 版权归 瞄你个汪 所有。使用本代码应遵守相关法律法规和Apache 2.0开源许可要求。
package top.geeke.toolkit.http;

import cn.hutool.json.JSONUtil;
import lombok.Getter;
import top.geeke.eunm.SysErrorEnum;

/**
 * <p>
 * Http 响应类
 * </p>
 * @author 瞄你个汪
 * @since 2024-05-01 12:00:00
 */
@Getter
public class Result<T> {
    /**
     * 响应代码
     */
    private int code;

    /**
     * 响应消息
     */
    private String message;

    /**
     * 响应结果
     */
    private T result;

    public Result(ResultEnum result) {
        this.message = result.message;
        this.code = result.code;
    }

    public Result(ResultEnum result, T data) {
        this(result);
        this.result = data;
    }

    public Result(int code, String message) {
        this.message = message;
        this.code = code;
    }

    /**
     * 成功
     */
    public static <T> Result<T> ok() {
        return ok(null);
    }

    /**
     * 成功
     */
    public static <T> Result<T> ok(T data) {
        return new Result<>(ResultEnum.R200, data);
    }

    /**
     * 失败
     */
    public static <T> Result<T> error(int code, String message) {
        return new Result<>(code, message);
    }

    /**
     * 失败
     */
    public static <T> Result<T> error(Exception error) {
        return new Result<>(ResultEnum.R400.code, error.getMessage());
    }

    /**
     * 失败
     */
    public static <T> Result<T> error(String message) {
        return Result.error(ResultEnum.R400.code, message);
    }

    /**
     * 失败
     */
    public static <T> Result<T> error(String message, Object... args) {
        return Result.error(ResultEnum.R400.code, String.format(message, args));
    }

    /**
     * 失败
     */
    public static <T> Result<T> error(SysErrorEnum error) {
        return Result.error(error.value, error.text);
    }

    /**
     * 失败
     */
    public static <T> Result<T> error(SysErrorEnum error, Object... args) {
        return Result.error(error.value, String.format(error.text, args));
    }

    public Result<T> setCode(int code) {
        this.code = code;
        return this;
    }

    public Result<T> setMessage(String message) {
        this.message = message;
        return this;
    }

    public Result<T> setDate(T data) {
        this.result = data;
        return this;
    }

    @Override
    public String toString() {
        return JSONUtil.toJsonStr(this);
    }
}
